package com.sudo.common.controller;

import com.sudo.common.constant.UserConstant;
import com.sudo.common.utils.*;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @author 为道日损 2020-04-24 15:29
 */
public abstract class BaseController {

    protected boolean superName(String username) {
        return UserConstant.SUPER_NAME.equals(username);
    }
    protected boolean superAdmin(String roleCode) {
        return UserConstant.SUPER_ADMIN.equals(roleCode);
    }

    protected Map<String, String> getErrors(BindingResult result) {
        List<FieldError> errorList = result.getFieldErrors();
        Map<String, String> map = new HashMap<>();
        for (FieldError error : errorList) {
            //发生验证错误所对应的某一个属性
            String errorFiled = error.getField();
            //验证错误信息
            String errorMsg = error.getDefaultMessage();
            map.put(errorFiled, errorMsg);
        }
        return map;
    }

    protected String getFirstError(BindingResult result) {
        Map<String, Object> map = result.getModel();
        Object o = MapUtil.getFirstValueOrNull(map);
//        Field[] fields = o.getClass().getDeclaredFields();    // 只能获取当前类的属性
        Field[] fields = getAllFields(o);                       // 可以获取父类的属性

        for (Field field : fields) {
            FieldError fieldError = result.getFieldError(field.getName());
            if (null != fieldError) {
                return fieldError.getDefaultMessage();
            }
        }
        return null;
    }

    private static Field[] getAllFields(Object object){
        Class clazz = object.getClass();
        List fieldList = new ArrayList<>();
        while (clazz != null){
            fieldList.addAll(Arrays.asList(clazz.getDeclaredFields()));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        return fields;
    }

}
